# GNAFU - "Ground, Navy and Air Fuck-Up" real-time strategy game
# Copyright (C) 2008-2009 k0wax <k0waxk0wax@gmail.com>
#
# This file is part of GNAFU.
#
# GNAFU is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# GNAFU is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with GNAFU.  If not, see <http://www.gnu.org/licenses/>.

"""Savegames"""
from __future__ import division, absolute_import
from cStringIO import StringIO
import shelve, copy, gc
import pyglet
from src import entity, xpickle

# patching shelve.{Pickler,Unpickler}
shelve.Pickler = xpickle.Pickler

def save(filename='savegame.sav'):
    from src import game
    gc.collect()
    d = shelve.open(filename)
    
    # entities
    entities = {}
    for id, obj in game.entityctl.entities.items():
        entities[id] = obj
    d['entities'] = entities
    print 'saved entities', entities.values()

    d['buildings'] = game.buildingctl.get_all_buildings()
    d['units'] = game.unitctl.get_all_units()
    d['field'] = game.field
    d['vp'] = game.vp

    d.close()

def load(filename='savegame.sav'):
    from src import game
    d = shelve.open(filename)

    '''
    print 'LOAD Entities:', d['entities']
    print 'LOAD Buildings:', d['buildings']
    print 'LOAD Field:', d['field']
    print 'LOAD Units:', d['units']
    print 'LOAD VP:', d['vp']
    '''
    print 'loading...'
    game.field = d['field']
    game.vp = d['vp']
    game.entityctl.entities.update(d['entities'])
    game.buildingctl.buildings = d['buildings']
    game.unitctl.units = d['units']
    #print '//////////', game.buildingctl.get_all_buildings()
    #print d['buildings'][0].__dict__

    d.close()
